<template>
  <!-- header框 -->
    <div style="background-color:white;">
        <el-row>
            <!-- logo -->
            <el-col :span="12">
                <el-image style="margin-left: 20px;height: 100px;width: auto;" src="image/login/DADARecipes.jpg" @click="navigateToHome"></el-image>
            </el-col>
            <!-- 搜索框 -->
            <el-col :span="12" style="padding-top: 35px;padding-left: 250px">
                <el-input style="height: 35px;width: 300px;border: red 3px solid;border-radius: 0px;" placeholder="请输入搜索内容" v-model="search"></el-input>
                <el-button style="border: red 3px solid;height: 35px;width: auto;border-radius: 0px;background-color:red;color: white">搜索</el-button>
            </el-col>
        </el-row>
    </div>
  <!-- 条件查询框 -->
    <div style="background-color:white;padding-bottom: 20px">
        <el-row>
            <!-- 购物车商品总数 -->
            <el-col :span="2" style="padding-top: 5px">
                <span style="color: red;font-size: 20px;padding-left: 20px;padding-top: 5px">我的购物车</span>
            </el-col>
        </el-row>
    </div>
  <!-- 购物车操作栏 -->
    <div style="background-color:lightgrey;">
        <el-row>
            <el-col :span="24" style="border-bottom: 3px solid #777777">
                <!-- 全选按钮 -->
                <el-checkbox style="padding-left: 30px" v-model="isAllSelected" @change="toggleAllSelection">全选</el-checkbox>
                <span style="font-size: 15px;padding-left: 250px">商品</span>
                <span style="font-size: 15px;padding-left: 450px">价格</span>
                <span style="font-size: 15px;padding-left: 200px">数量</span>
                <span style="font-size: 15px;padding-left: 200px">操作</span>
            </el-col>
        </el-row>
    </div>
  <!-- 购物车商品卡片 -->
    <div style="background-color:#BBDEFB;">
        <el-row v-for="item in shopList" :key="item.shopId">
            <el-col :span="24">
                <el-card style="padding: 10px">
                    <el-row :span="3">
                        <el-checkbox
                                    true-value="1"
                                    false-value="0"
                                    v-model="item.status"
                                    @change="updateStatus(item)"
                        >
                          <span>{{item.shopId}}</span></el-checkbox>
                    </el-row>
                    <el-row :span="21" style="margin-top: 10px">
                        <!-- 商品图片 -->
<!--                         <el-image :src="'http://localhost:9090'+product.productImg" alt="User Avatar" class="product-image"></el-image>-->
                        <el-image :src="baseUrl+item.productImg" style="width: 120px;height: 120px"></el-image>
                        <!-- 商品描述 -->
                        <span style="border:1px solid #fff;width: 300px;padding-left:80px;padding-top: 20px">{{item.productName}}</span>
                        <!-- 商品价格 -->
                        <span style="padding-left: 260px;padding-top: 25px;color: red;font-weight: bold;font-size: large">
                        ￥{{(item.price * item.quantity).toFixed(1)}}</span>
                        <!-- 商品数量 -->
                        <el-input-number :min="1" style="height: 30px;margin-top: 25px;margin-left: 145px" v-model="item.quantity" @change="updateTotalPrice"></el-input-number>
                        <!-- 操作 -->
                        <el-button link type="primary" style="padding-left: 120px;margin-top: -50px" @click="deleteProduct(item.productId)">删除商品</el-button>
                    </el-row>
                </el-card>
            </el-col>
        </el-row>
    </div>
  <!-- 购物车阶段部分 -->
    <div style="background-color:white;">
        <el-row>
            <el-col>
                <span style="margin-left: 1200px;color: #777777;font-size: small">^已选择 {{ selectedItemsCount }} 件商品</span>
            </el-col>
            <el-col style="margin-left: 1200px">
                <span style="padding-right: 10px;color: #777777;font-size: small">总价:</span>
                <span style="color: red;font-size: large">￥{{ totalPrice }}</span>
                <el-button type="danger" plain size="large" style="margin-left: 10px;margin-bottom: 10px" @click="checkout">结算</el-button>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import {ref, computed, onMounted} from "vue";
import router from "@/router";
import axios from "axios";
import {ElMessage} from "element-plus";
import qs from "qs";

//从localstorage中获取用户id
const user =ref(getUser())

const baseUrl = getBaseUrl();
// 定义方法用于跳转到首页
const navigateToHome = () => {
    router.push('/index');
};



// 定义列表用于保存地址
const addressList = ref([
    { province: '广东省', city: '深圳市', district: '龙岗区', address: 'xxx街道', phone: '12345678901'}
]);

// 定义列表用于保存店铺信息和商品信息
const shopList = ref([
    // { shopId: 1, shopName: 'xxxx旗舰店', productDescription: "新鲜现挖带泥胡萝卜当季农家自种萝卜脆爽多汁水果蔬菜 新鲜胡萝卜 2斤 带箱", productPrice: 10.9, proNum: 1, productImg: "/image/login/carrot1.jpeg", selected: false },
    // { shopId: 2, shopName: 'yyyy旗舰店', productDescription: "北蔬 大叶菠菜种子红根秋冬天四季蔬菜种籽 卓脆红根大叶菠菜种子10g", productPrice: 12.5, proNum: 1, productImg: "/image/login/bc1.jpg", selected: false },
    // { shopId: 3, shopName: 'zzzz旗舰店', productDescription: "山东生吃粉瓤西红柿 新鲜沙瓤大番茄 粉瓤西红柿 5斤 家庭款", productPrice: 9.9, proNum: 1, productImg: "/image/login/xhs1.jpg", selected: false }
]);

// 定义变量用于存储搜索框中的内容
const search = ref('');

// 全选状态
const isAllSelected = ref(false);

// 计算选中商品的数量
const selectedItemsCount = computed(() => {
    return shopList.value.filter(item => item.selected).length;
});

// 计算总价
const totalPrice = ref("");

const updateStatus = (item)=>{
  let data=qs.stringify({
    userId:user.value.id,
    productId:item.productId,
    status:item.status,
    quantity:item.quantity
  })
  axios.post(BASE_URL+"/v1/cart/updateProducts",data).then((response)=>{
    if(response.data.code===2000){

    }else{
      ElMessage.error(response.data.msg);
    }
  })
  updateTotalPrice()
}

// 更新总价
const updateTotalPrice = () => {
  let total =0;
  for (let i = 0; i < shopList.value.length; i++){
    if(shopList.value[i].status==="1"){
      total+=shopList.value[i].price*shopList.value[i].quantity;
    }
  }

  totalPrice.value= total.toFixed(1);
};

// 切换全选状态
const toggleAllSelection = (value) => {
    shopList.value.forEach(item => item.selected = value);
};

const deleteProduct = (productId) => {
      let data1={
        userId:user.value.id,
        productId:productId
      }
      let data = qs.stringify(data1);
    // 这里可以添加删除商品逻辑
    console.log('删除商品', productId);
    axios.post(BASE_URL + "/v1/cart/deleteProducts/" ,data)
        .then(response => {
            if (response.data.code === 2000) {
                ElMessage.success('删除成功');
                queryCart();
            } else {
                ElMessage.error(response.data.msg);
            }
        })
};

// 删除商品
const removeItem = (item) => {
    shopList.value = shopList.value.filter(i => i !== item);
    updateTotalPrice();
};

// 结算
const checkout = () => {
    let data = qs.stringify({
        userId: user.value.id,
        shippingAddressId:'101',
    })
  axios.post(BASE_URL+"/v1/cart/addOrder",data).then((response)=>{
    if(response.data.code===2000){
      ElMessage.success('下单成功');
    }else{
      ElMessage.error(response.data.msg);
    }
  })
    router.push('/orderDetails');
};



//定义方法向后端发送请求获取地址数据
const selectAddress =()=>{
  const userId=user.value.id;
  let data = qs.stringify({
    userId:userId
  })
  axios.get(BASE_URL+"/v1/user/selectAddress?"+data).then((response)=>{
    if(response.data.code===2000){
      //将返回的结果赋值到addressList
      addressList.value=response.data.data;
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}
//绑定收获地址
const address=ref();

onMounted(()=>{
  //自动挂载地址数据
  selectAddress();
  //自动挂载购物车数据
  queryCart();
})
//定义方法查询已完成购物车数据
const queryCart=()=>{
  const  userId=user.value.id;
  axios.get(BASE_URL+"/v1/cart/select/"+userId).then((response)=>{
    if(response.data.code===2000){
      //将返回的数据返回的shopList中
      shopList.value=response.data.data;
    }
    else if (response.data.code===5000){

    }
    else{
      ElMessage.error(response.data.msg);
    }
  })
  updateTotalPrice();
}


//定义方法用于更新购物车商品状态 传参：userId,status(0表示未选中 1表示选中状态),productId,productNum
const updateCartProduct =(item)=>{
  let data = {
    status:'',
    userId:'',
    productId:'',
    quantity:''
  };
  //判断status的数据
  if(item.value.status == 0){
    data.status='1';
  }else if(item.value.status == 1){
    data.status='0';
  }
   data = qs.stringify({
    userId:user.value.id,
    productId:item.productId,
    quantity:item.quantity
  })
  axios.post(BASE_URL+"/v1/cart/updateProducts",data).then((response)=>{
    if(response.data.code===2000){

    }else{
      ElMessage.error(response.data.msg);
    }
  })
}

</script>

<style scoped>
</style>
